import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pica_acg/DataBaseFunction.dart';
import 'package:pica_acg/GlobalKey.dart';
// ignore: unused_import
import 'package:pica_acg/GlobalNetWorkReturnDefind.dart'; //@a 全局默认数据
// ignore: unused_import
import 'package:pica_acg/GlobalSettings.dart'; //@a 全局设置
import 'package:pica_acg/GlobalVarlable.dart';
// ignore: unused_import
import 'package:pica_acg/Pages/Category/Category.dart'; //@a 分类
// ignore: unused_import
import 'package:pica_acg/Pages/Comics/ComicsContorller.dart'; //@a 分类目录
// ignore: unused_import
import 'package:pica_acg/Pages/ComicsInfo/ComicsInfoController.dart'; //@a 漫画信息
// ignore: unused_import
import 'package:pica_acg/Pages/ComicsInfoDownload/ComicsInfoDownloadController.dart'; //@a 漫画下载页面
// ignore: unused_import
import 'package:pica_acg/Pages/Comment/CommentController.dart'; //@a 评论页面
import 'package:pica_acg/Pages/Comment/InfiniteSonComment/InfiniteSonCommentController.dart';
// ignore: unused_import
import 'package:pica_acg/Pages/Download/DownloadController.dart'; //@a 下载页面
// ignore: unused_import
import 'package:pica_acg/Pages/Home/Home.dart'; //@a 主页
// ignore: unused_import
import 'package:pica_acg/Pages/My/My.dart'; //@a 我的
// ignore: unused_import
import 'package:pica_acg/Pages/ReadingComics/ReadingComicsController.dart'; //@a 读漫画
// ignore: unused_import
import 'package:pica_acg/Pages/ReadingComics/Widget/Tips/ReadingComicsTipsController.dart'; //@a 读漫画的 提示
// ignore: unused_import
import 'package:pica_acg/Pages/Search/SearchController.dart'; //@a 搜索页面
// ignore: unused_import
import 'package:pica_acg/Pages/ServiceBranch/ServiceBranch.dart'; //@a 第一页 进入的首页选择分流
// ignore: unused_import
import 'package:pica_acg/Pages/ServiceList/ServiceList.dart'; //@a 选择服务器
// ignore: unused_import
import 'package:pica_acg/Pages/ServiceList/Widget/Mask/Widget/ServiceListBranchListViewBranchListViewList/LoadingController.dart';
// ignore: unused_import
import 'package:pica_acg/Pages/Settings/SettingsContorller.dart'; //@a 设置页面
import 'package:pica_acg/tools/Controller/Download/PlayDownload.dart'; //@a 开始下载
import 'package:pica_acg/tools/Db/Json/ComicsInfoDownload/DataBaseUserSetting.dart'; //@a 用户数据库
import 'package:screen/screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  @override
  void deleteFile() async {
    //删除根目录
    var sDocumentDir1 = (await getApplicationDocumentsDirectory()).path;
    var file = Directory(sDocumentDir1);
    file.delete(recursive: true);
    return;
  }

  mainStartDown() {
    PlayDownload.getDownLoad(); //继续下载之前没下完的
  }

  void fileList() async {
    //显示错有文件
    var sDocumentDir = (await getApplicationDocumentsDirectory());
    Stream<FileSystemEntity> entityList =
        sDocumentDir.list(recursive: true, followLinks: false);
    await for (FileSystemEntity entity in entityList) {
      //文件、目录和链接��继承自FileSystemEntity
      //FileSystemEntity.type静态函数返回值为FileSystemEntityType
      //FileSystemEntityType有三个常量：
      //Directory、FILE、LINK、NOT_FOUND
      //FileSystemEntity.isFile .isLink .isDerectory可用于判断类型
      print(entity.path);
    }
  }

  void initState() {
    //在这里可以优化 思路 开始不读取下载进度到时候打开那个页面载入那个下载进度
    super.initState();
    necessaryInitialization(); //必要的初始化

    // deleteFile();
    // fileList();
    // openFile();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
      resizeToAvoidBottomInset: true,
      /* appBar: AppBar(
        title: Text('Material App Bar'),
      ), */
      body: Center(
        child: Container(
          // child: My(), //我的
          // child: DownloadController(), //下载列表
          child: ServiceBranch(),
          /*    child: ServiceList(
            login: true, //是否需要登陆
            key: serviceListState,
            serviceUrl: 'https://picaapi.picacomic.com/',
          ), */
          // child: Loading2(url: "http://sakura.nat300.top/api/Index"),
          // child: MainHome(), //首页
          // child: Category(), //分类
          // child: ComicsContorller(title: '禁書目錄'), //漫画列表
          /*  child: ComicsInfoController(
            title: '暗杀教室',
            author: [],
            categories: ['aa', 'bb', 'cc'],
            likeNumber: 520,
            comicsId: '5821a9235f6b9a4f93f34449',
          ), //漫画信息 */
          /*    child: ComicsInfoDownloadController(
            comicsId: '58ca8475c91ae84c234c607b',
            title: "魔劍觸手3 COMIC ExE 04 ",
            chapter: AllChapterList.fromJson($netWorkAllChapter),
          ), */
          /*     child: ReadingComicsController(
            context: context,
            pageName: "第2集",
            comicsName: "暗杀教室",
            comicsId: "5c8941bbb9497270670798e1",
            subsectionId: "5c8941bbb9497270670798e3",
          ), //读漫画 */
          /*  child: CommentController(
            bookId:
                "book-pe8lnx-fj6oqfcwszwg6qscrhj2xyfat7hwgsiuexaqr34lydebkxauokvpcf5bhtw8ljk67iz5zfwu6litjrpkcv6g0mqcdshp49zj4itjg72c7noqdpqo7yx2",
            subsectionId:null,
            bookName: "暗杀教室",
          ), */
          /* child: InfiniteSonCommentController(
            bookId:
                'book-pe8lnx-fj6oqfcwszwg6qscrhj2xyfat7hwgsiuexaqr34lydebkxauokvpcf5bhtw8ljk67iz5zfwu6litjrpkcv6g0mqcdshp49zj4itjg72c7noqdpqo7yx2',
            title: '正在查看:初雪樱 的评论',
            commentId:
                "son-comment-ssairmfhzvfyikdpj3l7p0xljaz1y8wno00pwt8029077z7vak9971q1xpfplptqu671c9jz2myr08y0b6xm62kr1dluv34a4k7jktr7v75w",
            commentTableName: 'book_comment_son_kzrp4pg4puf5fxkjioemgbwbe5y6fwhg',
            initiaWidget: Container(
              child: Container(
                child: Container(
                  child: Container(
                    margin: EdgeInsets.only(
                      left: ScreenUtil().setWidth(20),
                      right: ScreenUtil().setWidth(20),
                      top: ScreenUtil().setHeight(20),
                    ),
                  ),
                ),
              ),
            ),
          ), */
          // child: SettingContorller(), //设置页面
          // child: SearchController(),
        ),
      ),
    );
  }
}

necessaryInitialization() async {
  //必要的初始化
  await setDocumentSrc();
  // await createInitializationFile(); //创建用户设置文件//!已放弃请勿使用
  readSettingsTable(); //读取用户设置

  dataBaseSelect(
    //初始化下载列表 查询全部的下载列表 加入到下载变量里
    "BookDownloadChapterList",
    'Progress != ?',
    ["null"],
  ).then((info) {
    /* Future.delayed(Duration(seconds: 5), () {
        print('downList');
        print(downList);
      }); */
    for (var item in info) {
      // 5da89805fc84c83fc017586b
      if (downList[item['BookId']] == null) {
        downList[item['BookId']] = {};
      }
      if (item["Download"] == 1) {
        //是否开始下载
        if (item["Success"] == 1) {
          //是否下载完成

          downList[item['BookId']][item['ChapterId']] = {
            "Title": '${item["Title"]}', //分卷名
            "Revised": true,
            "Color": {
              'Color': Color(0xff00a656),
              'TextColor': Color(0xffffffff),
            },
            "Extends": {
              "Download": true,
              "Success": true,
              "Progress": 1.0,
              "SetProgress": false,
            }
          };
        } else {
          //没下载完成 此时不一定是下载没成功也有可能是 99.xx 因为 一个漫画有三个图片 下载进度是 100的话 就会变成99.9
          //所以要再去images表查看是否下载完了
          dataBaseSelect(
            "BookDownloadChapterImagesList",
            'BookId = ? and ChapterId = ? and DownloadSuccess = ?',
            [
              item['BookId'],
              item['ChapterId'],
              false,
            ],
          ).then((bookDownloadChapterImagesList) {
            if (bookDownloadChapterImagesList.length == 0) {
              dataBaseUpdate(
                //初始化下载列表 查询全部的下载列表 加入到下载变量里
                "BookDownloadChapterList",
                {
                  "Progress": 1,
                  "Success": true,
                },
                'Progress != ?',
                ["null"],
              ).then((info) {});
              downList[item['BookId']][item['ChapterId']] = {
                "Title": '${item["Title"]}', //分卷名
                "Revised": true,
                "Color": {
                  'Color': Color(0xff00a656),
                  'TextColor': Color(0xffffffff),
                },
                "Extends": {
                  "Download": true,
                  "Success": true,
                  "Progress": 1.0,
                  "SetProgress": false,
                }
              };
            } else {
              //上面查�������据返回���确实是没下载完
              downList[item['BookId']][item['ChapterId']] = {
                "Title": '${item["Title"]}', //分卷名
                "Revised": true,
                "Color": {
                  'Color': Color(0xffff9a05),
                  'TextColor': Color(0xffffffff),
                },
                "Extends": {
                  "Download": false,
                  "Success": false,
                  "Progress": item["Progress"],
                  "SetProgress": false,
                }
              };
            }
          });
        }
      } else {
        //没下载 只加入下载列表

        downList[item['BookId']][item['ChapterId']] = {
          "Title": '${item["Title"]}', //分卷名
          "Revised": true,
          "Color": {
            'Color': Color(0xffec97b6),
            'TextColor': Color(0xffffffff),
          },
          "Extends": {
            "Download": false,
            "Success": false,
            "Progress": 0.0,
            "SetProgress": false,
          }
        };
      }
    }
  });

  PlayDownload.getDownLoad(); //继续下载之前没下完的
  Screen.brightness.then(
    (value) => brightness = value * 100, //获取屏幕亮度
  );
}

Future<Null> setDocumentSrc() async {
  //初始化存储路径F
  dataSpace = (await getApplicationDocumentsDirectory()).path;
  return;
}

openFile() async {
  final file = File(dataSpace +
      "/Cartoon/5da89805fc84c83fc017586b/5da89805fc84c83fc017586f/77.jpg");
  print(file);
}

readSettingsTable() {
  dataBaseSelect('UserSetting', 'id = ?', [1]).then((data) {
    if (data.length == 0) {
      //判断是不是没有数据 没有就插入默认数据
      dataBaseInsert('UserSetting', {
        "ScreenOrientation": false,
        "PageTurningMode": false,
        "PageTurningInterval": 0.5,
        "NightMode": false,
        "AddDownloadTips": true,
        "OpenAppToContinueDownloading": false,
      });
    } else {
      setting = DataBaseUserSetting.fromJson(data[0]);
      try {
        settingSettingBodyContorllerState.currentState.updateView();
      } catch (e) {}
    }
  });
}

/* Future<Null> createInitializationFile() async {
  //已弃用 本想吧设置信息写出文件 现放弃 改写入数据库
  //创建初始化文件
  /* var sDocumentDir = (await getApplicationDocumentsDirectory());
  Stream<FileSystemEntity> entityList =
      sDocumentDir.list(recursive: true, followLinks: false);
  await for (FileSystemEntity entity in entityList) {
    //文件、目录和链接��继承自FileSystemEntity
    //FileSystemEntity.type静态函数返回值为FileSystemEntityType
    //FileSystemEntityType有三个常量：
    //Directory、FILE、LINK、NOT_FOUND
    //FileSystemEntity.isFile .isLink .isDerectory可用于判断类型
    print(entity.path);
  } */
  final file = File(documentSrc + "/UsetSetting/Undefined/Setting.PicaAcg");
  bool dirBool = await file.exists(); //返回真假 文件是否存在
  print(dirBool);
  if (!dirBool) {
    Directory(documentSrc + "/UsetSetting").create();
    Directory(documentSrc + "/UsetSetting/Undefined").create();

    File(documentSrc + "/UsetSetting/Undefined/Setting.PicaAcg")
        .writeAsBytes( null);
  } else {
    /*  File(documentSrc + "/UsetSetting/Undefined/Setting.PicaAcg")
        .writeAsString("aaaa"); */
  }
} */
